package com.chaodev.base.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.chaodev.base.dao.ActivityDao;
import com.chaodev.base.dao.AttDao;
import com.chaodev.base.dao.CommDao;
import com.chaodev.base.dao.NoticeDao;
import com.chaodev.base.dto.ActivityNoticeDto;
import com.chaodev.base.dto.ActivitySignUpDto;
import com.chaodev.base.em.BizTypeEnum;
import com.chaodev.base.em.OperEnum;
import com.chaodev.base.model.*;
import com.chaodev.base.service.ActivityServie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * vcbase
 *
 * @author 95634
 * @描述
 * @date 2023/5/17 17:21
 **/
@Service
public class ActivityServieImpl implements ActivityServie {

    @Autowired
    private ActivityDao dao;

    @Autowired
    private CommDao commDao;

    @Autowired
    private AttDao attDao;

    @Autowired
    NoticeDao noticeDao;

    private static final SimpleDateFormat DAY_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public PageInfo<ActivityNotice> queryPageList(ActivityNoticeDto dto) {
        PageHelper.startPage(dto.getPage(), dto.getRows());
        ActivityNotice activityNotice = new ActivityNotice();
        BeanUtil.copyProperties(dto, activityNotice);
        List<ActivityNotice> list = dao.getActivityNot(activityNotice);
        Att att = null;
        List<Att> attList;
        for (ActivityNotice notice : list) {
            att = new Att();
            att.setDataNo(notice.getId());
            att.setState(1);
            att.setBizType(BizTypeEnum.Em_Notice.getValue());
            attList = attDao.queryDataList(att);
            notice.setAtts(attList.stream().filter(d -> "fm".equals(d.getAddType())).collect(Collectors.toList()));
            notice.setAnnex(attList.stream().filter(d -> "fj".equals(d.getAddType())).collect(Collectors.toList()));
        }
        PageInfo<ActivityNotice> pageInfo = new PageInfo<>(list, dto.getRows());
        return pageInfo;
    }

    @Override
    public PageInfo<ActivityNotice> queryMyPageList(int pae, int rows, ActivityNotice dto) {
        PageHelper.startPage(pae, rows);
        List<ActivityNotice> list = dao.getActivityNot(dto);
        Att att = null;
        List<Att> attList;
        for (ActivityNotice activityNotice : list) {
            att = new Att();
            att.setDataNo(activityNotice.getId());
            att.setState(1);
            att.setBizType(BizTypeEnum.Em_Notice.getValue());
            attList = attDao.queryDataList(att);
            activityNotice.setAtts(attList.stream().filter(d -> "fm".equals(d.getAddType())).collect(Collectors.toList()));
            activityNotice.setAnnex(attList.stream().filter(d -> "fj".equals(d.getAddType())).collect(Collectors.toList()));
        }
        PageInfo<ActivityNotice> pageInfo = new PageInfo<>(list, rows);
        return pageInfo;
    }

    @Override
    public PageInfo<ActivityNotice> getMyNoSignUpActivity(int pae, int rows, ActivityNotice dto) {
        PageHelper.startPage(pae, rows);
        List<ActivityNotice> list = dao.getActivityNot(dto);
        Att att = null;
        List<Att> attList;
        for (ActivityNotice activityNotice : list) {
            att = new Att();
            att.setDataNo(activityNotice.getId());
            att.setState(1);
            att.setBizType(BizTypeEnum.Em_Notice.getValue());
            attList = attDao.queryDataList(att);
            activityNotice.setAtts(attList.stream().filter(d -> "fm".equals(d.getAddType())).collect(Collectors.toList()));
            activityNotice.setAnnex(attList.stream().filter(d -> "fj".equals(d.getAddType())).collect(Collectors.toList()));
        }
        PageInfo<ActivityNotice> pageInfo = new PageInfo<>(list, rows);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveData(ActivityNotice activityNotice, UserInfo userInfo) {
        if (ObjectUtil.isNotNull(activityNotice.getId()) && activityNotice.getId() > 0) {
            dao.updateDataById(activityNotice);
        } else {
            dao.insertData(activityNotice);

            ApplyLc applyLc = new ApplyLc();
            applyLc.setBizType(BizTypeEnum.Em_Notice.getValue());
            applyLc.setBizId(activityNotice.getId());
            applyLc.setReqState(1);
            applyLc.setLcId("lc_001");
            applyLc.setResultCode(OperEnum.Em_Add.getValue());
            applyLc.setResultDsc(OperEnum.Em_Add.getName());
            applyLc.setOpr(userInfo.getUserId());
            applyLc.setOpTime(new Date());
            applyLc.setState(2);
            commDao.saveApply(applyLc);

            ApplyStateToNext stateToNext = new ApplyStateToNext();
            stateToNext.setBizType("1000");
            stateToNext.setReqState(1);
            stateToNext.setNowLcId("lc_001");
            stateToNext.setOp(OperEnum.Em_Add.getValue());
            ApplyStateToNext nextFlowInfo = commDao.getNextFlowInfo(stateToNext);

            Task task = new Task();
            task.setBizType(BizTypeEnum.Em_Notice.getValue());
            task.setTitle(activityNotice.getTheme());
            task.setBizId(activityNotice.getId());
            task.setLcId(nextFlowInfo.getNextLcId());
            task.setLcName(nextFlowInfo.getNextLcName());
            task.setCUser(userInfo.getUserId());
            task.setState(1);
            commDao.saveTask(task);

            applyLc = new ApplyLc();
            applyLc.setBizType(BizTypeEnum.Em_Notice.getValue());
            applyLc.setBizId(activityNotice.getId());
            applyLc.setReqState(1);
            if (StrUtil.isNotEmpty(nextFlowInfo.getNextLcId())) {
                applyLc.setLcId(nextFlowInfo.getNextLcId());
            }
            applyLc.setState(1);
            commDao.saveApply(applyLc);
        }
        if (activityNotice.getAtts().size() > 0) {
            attDao.deleteDataByDataNo(String.valueOf(activityNotice.getId()), BizTypeEnum.Em_Notice.getValue());
            for (Att att : activityNotice.getAtts()) {
                att.setBizType(BizTypeEnum.Em_Notice.getValue());
                att.setDataNo(activityNotice.getId());
                att.setcUser(userInfo.getUserId());
                att.setAddType("fm");
                attDao.insertData(att);
            }
        }
        if (activityNotice.getAnnex().size() > 0) {
            if (activityNotice.getAtts().size() == 0) {
                attDao.deleteDataByDataNo(String.valueOf(activityNotice.getId()), BizTypeEnum.Em_Notice.getValue());
            }
            for (Att att : activityNotice.getAnnex()) {
                att.setBizType(BizTypeEnum.Em_Notice.getValue());
                att.setDataNo(activityNotice.getId());
                att.setcUser(userInfo.getUserId());
                att.setAddType("fj");
                attDao.insertData(att);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDataById(ActivityNotice tbActivityNotice) {
        dao.updateDataById(tbActivityNotice);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDataById(String id) {
        dao.deleteDataById(id);
        attDao.deleteDataByDataNo(id, BizTypeEnum.Em_Notice.getValue());
        Task task = new Task();
        task.setBizType(BizTypeEnum.Em_Article.getValue());
        task.setDelId(id);
        commDao.delTask(task);
    }

    @Override
    public List<ActivityNotice> queryDataList(ActivityNotice tbActivityNotice) {
        return dao.getActivityNot(tbActivityNotice);
    }

    @Override
    public ActivitySignUp findSignUpDataById(String id) {
        return dao.findSignUpDataById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSignUpData(ActivitySignUp activitySignUp) throws DataAccessException {
        if (ObjectUtil.isNotNull(activitySignUp.getId()) && activitySignUp.getId() > 0) {
            dao.updateSignUpDataById(activitySignUp);
        } else {
            Task task = new Task();
            task.setBizId(activitySignUp.getActivityId());
            task.setBizType(BizTypeEnum.Em_Notice.getValue());
            Task task1 = commDao.getTask(task);
            if (task1 == null || task1.getState() != 4) {
                throw new RuntimeException("活动还未审核，还不能报名，请耐心等待");
            }
            ActivityNotice dataById = dao.findDataById(String.valueOf(activitySignUp.getActivityId()));
            int total = Integer.parseInt(Optional.of(dataById.getPeopleNum()).orElse("0"));
            ActivitySignUp signUpOb = new ActivitySignUp();
            signUpOb.setActivityId(activitySignUp.getActivityId());
            signUpOb.setState(1);
            List<ActivitySignUp> signUps = dao.querySignUpDataList(signUpOb);
            int lastnum = total - signUps.size();
            if (lastnum == 0) {
                throw new RuntimeException("报名人数已满，不能报名");
            }
            ActivitySignUp signUp = new ActivitySignUp();
            signUp.setActivityId(activitySignUp.getActivityId());
            signUp.setSignUpUserCode(activitySignUp.getSignUpUserCode());
            List<ActivitySignUp> activitySignUps = dao.querySignUpDataList(signUp);
            if (activitySignUps.size() > 0) {
                throw new RuntimeException("您已经报名过，无效再次报名");
            } else {
                dao.insertSignUpData(activitySignUp);
                ActivityNotice activityNotice = dao.findDataById(String.valueOf(activitySignUp.getActivityId()));
                Notice notice = new Notice();
                notice.setCreateUser(activitySignUp.getSignUpUserCode());
                notice.setBusinessType("sign up");
                notice.setTitle("系统消息");
                notice.setContent("您已成功报名" + activityNotice.getTheme() + ",请按时参加");
                notice.setEndDate(DAY_FORMAT.format(activityNotice.getEndTime()));
                notice.setMenuId(String.valueOf(activitySignUp.getActivityId()));
                noticeDao.noticeAddMysql(notice);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertSignUpData(ActivitySignUp tbActivitySignUp) throws DataAccessException {
        dao.insertSignUpData(tbActivitySignUp);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSignUpDataById(ActivitySignUp tbActivitySignUp) throws DataAccessException {
        dao.updateSignUpDataById(tbActivitySignUp);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSignUpDataById(String id) throws DataAccessException {
        dao.deleteSignUpDataById(id);
    }

    @Override
    public List<ActivitySignUp> querySignUpDataList(ActivitySignUp tbActivitySignUp) {
        return dao.querySignUpDataList(tbActivitySignUp);
    }

    @Override
    public PageInfo<ActivitySignUp> querySignUpPageList(ActivitySignUpDto tbActivitySignUp) {
        PageHelper.startPage(tbActivitySignUp.getPage(), tbActivitySignUp.getRows());
        ActivitySignUp activitySignUp = new ActivitySignUp();
        BeanUtil.copyProperties(tbActivitySignUp, activitySignUp);
        List<ActivitySignUp> tbActivitySignUpList = dao.querySignUpDataList(activitySignUp);
        PageInfo<ActivitySignUp> pageInfo = new PageInfo<ActivitySignUp>(tbActivitySignUpList, tbActivitySignUp.getRows());
        return pageInfo;
    }

    @Override
    public ActivityNotice findDataById(String id) {
        ActivityNotice dataById = dao.findDataById(id);
        Att att = new Att();
        att.setDataNo(Integer.parseInt(id));
        att.setState(1);
        att.setBizType(BizTypeEnum.Em_Notice.getValue());
        dataById.setAtts(attDao.queryDataList(att));
        return dataById;
    }

    @Override
    public PageInfo<ActivityNotice> getMySignUpAct(ActivityNoticeDto dto, UserInfo userInfo) {
        PageHelper.startPage(dto.getPage(), dto.getRows());
        ActivityNotice activityNotice = new ActivityNotice();
        BeanUtil.copyProperties(dto, activityNotice);
        activityNotice.setCUser(userInfo.getUserId());
        List<ActivityNotice> activitylist = dao.getMySignUpAct(activityNotice);
        Att att = null;
        List<Att> attList;
        for (ActivityNotice notice : activitylist) {
            att = new Att();
            att.setDataNo(notice.getId());
            att.setState(1);
            att.setBizType(BizTypeEnum.Em_Notice.getValue());
            attList = attDao.queryDataList(att);
            notice.setAtts(attList.stream().filter(d -> "fm".equals(d.getAddType())).collect(Collectors.toList()));
            notice.setAnnex(attList.stream().filter(d -> "fj".equals(d.getAddType())).collect(Collectors.toList()));
        }
        PageInfo<ActivityNotice> pageInfo = new PageInfo<ActivityNotice>(activitylist, dto.getRows());
        return pageInfo;
    }
}
